package com.wanggsx.library.util.fun.webview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.wanggsx.library.R;
import com.wanggsx.library.base.view.BaseActivity;


/**
 * Created by wangweigang on 16/4/22.
 */
public class MyWebViewActivityWithTittleBar extends BaseActivity {
    public static final String URL = "URL";
    public static final String APPEND_JS = "APPEND_JS";

    private WebView myWebView;
    private RelativeLayout ivBack;
    private RelativeLayout ivRefresh;
    private TextView tvTitle;
    private ProgressBar mProgressbar;
    private String append_js;

    public interface OnPageChangeListener {
        //true表示需要处理，不用继续加载此url
        boolean onPageChange(Context context, String url);
    }

    private static OnPageChangeListener mOnPageChangeListener;

    public static void setOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
        mOnPageChangeListener = onPageChangeListener;
    }

    @Override
    public void setListener() {
        ivRefresh.setOnClickListener(this);
        ivBack.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle bundle) {
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("white"));
        getWindow().setDimAmount(0);
        String url = getIntent().getStringExtra(URL);
        append_js = getIntent().getStringExtra(APPEND_JS); //是否注入js（就是调js）
        WebSettings settings = myWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccessFromFileURLs(true);
        myWebView.loadUrl(url);
    }

    @Override
    public void doBusiness() {

    }

    @Override
    public void onWidgetClick(View view) {

    }

    @Override
    public boolean onBack() {
        finish();
        overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
        return true;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rlyt_exit_MyWebViewActivity) {
            onBack();
        } else if (id == R.id.rlyt_refresh_MyWebViewActivity) {
            if (mProgressbar.getVisibility() == View.VISIBLE) {
                myWebView.stopLoading();
            } else {
                myWebView.reload();
            }
        }
    }

    @Override
    public int setRootLayoutId() {
        return R.layout.activity_webview1;
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        myWebView = (WebView) findViewById(R.id.webview_activity);
        myWebView.clearCache(true);
        myWebView.clearHistory();
        // 为WebView设置WebViewClient处理某些操作
        WebSettings settings = myWebView.getSettings();
        settings.setJavaScriptEnabled(true);// 支持javascript
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        myWebView.setBackgroundColor(0);
        // 隐藏滚动条
        myWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        myWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tvTitle.setText(title);
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                view.draw(new Canvas());
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mProgressbar.setProgress(newProgress);
            }
        });
        myWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mProgressbar.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http")) {
                    return super.shouldOverrideUrlLoading(view, url);
                } else {
                    if (mOnPageChangeListener != null) {
                        return mOnPageChangeListener.onPageChange(MyWebViewActivityWithTittleBar.this, url);
                    }
                    return true;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //ivTitle.setText(view.getTitle());
                mProgressbar.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(append_js)) {
                    view.loadUrl("javascript:" + append_js);
                }
            }
        });
        ivRefresh = (RelativeLayout) findViewById(R.id.rlyt_exit_MyWebViewActivity);
        tvTitle = (TextView) findViewById(R.id.tv_title_MyWebViewActivity);
        mProgressbar = (ProgressBar) findViewById(R.id.iv_refresh_progressbar);
        ivBack = (RelativeLayout) findViewById(R.id.rlyt_refresh_MyWebViewActivity);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//监听返回键，如果可以后退就后退
            if (myWebView.canGoBack()) {
                myWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        mOnPageChangeListener = null;
        super.onDestroy();
    }
}
